package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.remark.LikeTimesDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;
import static com.tianji.common.constants.MqConstants.Queue.QA_LIKE_TIMES_QUEUE;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2025/7/4 14:54
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LikeTimesChangeListener {
    private final IInteractionReplyService replyService;

    /**
     * 1、监听回复点赞数变更的消息 -> 修改回复表对应的点赞次数（Day6 - 随堂3）
     *
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QA_LIKE_TIMES_QUEUE, durable = "true"),
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listenReplyLikeTimesChangeMsg(List<LikeTimesDTO> msgs) {
        // 1、消息健壮性判断
        if (ObjectUtil.isEmpty(msgs)) {
            log.error("点赞数消息格式异常，消息：{}", msgs);
            return;
        }

        // 2、根据主键ID更新点赞数
        List<InteractionReply> replies = new ArrayList<>(msgs.size());
        for (LikeTimesDTO msg : msgs) {
            InteractionReply reply = new InteractionReply().setId(msg.getBizId()).setLikedTimes(msg.getLikeTimes());
            replies.add(reply);
        }
        replyService.updateBatchById(replies);
    }
}
